package com.qd.system.importexcel.dict;

import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.exception.ExcelOperatorException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.sys.domain.entity.dict.DictTypeDTO;
import com.qd.system.model.DictType;
import com.qd.system.service.dict.DictTypeService;
import com.qd.system.service.dict.MbUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 码表类型,excel导入处理类
 *
 * @author sjk
 */
@Slf4j
public class DictTypeImportHandler {

    private final DictTypeService dictTypeService;
    private final ValidatorUtil validatorUtil;
    private final List<ImportErr> errorList;
    private final LocalDateTime now = LocalDateTime.now();

    public DictTypeImportHandler(DictTypeService dictTypeService, ValidatorUtil validatorUtil, List<ImportErr> errorList) {
        this.dictTypeService = dictTypeService;
        this.validatorUtil = validatorUtil;
        this.errorList = errorList;
    }

    /**
     * 处理具体导入
     *
     * @param rowList excel行数据集合，默认为1000行
     * @param results 异常信息存储
     */
    public void process(List<ExcelRowMsg<DictTypeDTO>> rowList, List<BatchResult> results) {
        final List<DictTypeDTO> dictTypeList = rowList.stream().map(ExcelRowMsg::getRowData).collect(toList());
        final List<String> existsIds = existsIds(dictTypeList);
        final int size = rowList.size();
        try {
            for (ExcelRowMsg<DictTypeDTO> excelRowMsg : rowList) {
                final DictTypeDTO dictTypeDto = excelRowMsg.getRowData();
                final ReadRowHolder readRowHolder = excelRowMsg.getReadRowHolder();
                final List<String> errors = buildImportDto(dictTypeDto);
                if (!errors.isEmpty()) {
                    errorList.add(ExcelUtil.buildError(readRowHolder, errors));
                }
            }
            if (!errorList.isEmpty()) {
                throw new ExcelOperatorException(errorList);
            } else {
                final List<DictType> addDictTypeList = new ArrayList<>(size);
                final List<DictType> updateDictTypeList = new ArrayList<>(size);
                doProcessDictData(existsIds, dictTypeList, addDictTypeList, updateDictTypeList);
                BatchResult.buildBatchResult(results, addDictTypeList.size(), updateDictTypeList.size());
                addDictTypeList.clear();
                updateDictTypeList.clear();
            }
        } finally {
            dictTypeList.clear();
            existsIds.clear();
        }
    }

    /**
     * 保存数据
     *
     * @param existsIds          已经存在的数据库主键
     * @param dictTypeList       excel行数据集合
     * @param addDictTypeList    添加集合
     * @param updateDictTypeList 更新集合
     */
    private void doProcessDictData(List<String> existsIds, List<DictTypeDTO> dictTypeList, List<DictType> addDictTypeList, List<DictType> updateDictTypeList) {
        dictTypeList.forEach(dictTypeDto -> {
            final DictType dictType = dictTypeService.dtoToModel(dictTypeDto);
            dictTypeService.clearCache(dictType);
            if (MbUtil.isExistInCollection(existsIds, dictTypeDto.getTypeId())) {
                dictType.setAddTime(null);
                dictType.setUpdateTime(now);
                updateDictTypeList.add(dictType);
            } else {
                dictType.setAddTime(now);
                dictType.setUpdateTime(null);
                addDictTypeList.add(dictType);
            }
        });
        if (!addDictTypeList.isEmpty()) {
            dictTypeService.saveBatch(addDictTypeList);
        }
        if (!updateDictTypeList.isEmpty()) {
            dictTypeService.updateBatchIds(updateDictTypeList);
        }
    }

    /**
     * 获得主键存在的集合
     *
     * @param dictTypeList excel行数据集合
     * @return 主键集合
     */
    private List<String> existsIds(List<DictTypeDTO> dictTypeList) {
        final List<String> ids = dictTypeList.stream().map(DictTypeDTO::getTypeId).collect(toList());
        final List<String> existsIds = dictTypeService.getBaseMapper().getIds(ids);
        ids.clear();
        return existsIds;
    }

    /**
     * 导入验证
     *
     * @param dictTypeDto 单个excel行数据
     * @return 异常信息
     */
    private List<String> buildImportDto(DictTypeDTO dictTypeDto) {
        final List<String> errors = new ArrayList<>();
        //验证信息，自己编写
        final Integer status = MbUtil.isStatusValidate(errors, dictTypeDto.getStatusDisplay());
        if (null != status) {
            dictTypeDto.setStatus(status);
        }
        importValidate(dictTypeDto, errors);
        return errors;
    }

    /**
     * 导入实体验证
     *
     * @param dictTypeDto 单个excel行数据
     * @param errors      异常信息存储
     */
    private void importValidate(DictTypeDTO dictTypeDto, List<String> errors) {
        if (errors.isEmpty()) {
            try {
                validatorUtil.checkValid(dictTypeDto, DefaultGroup.class);
            } catch (ConstraintViolationException e) {
                errors.addAll(validatorUtil.getValidationError(e));
            }
        }
    }
}